package com.lzx.iteam;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.adapter.CloudGroupAdapter;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imageloader.core.listener.PauseOnScrollListener;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hfx on 14-12-24.
 */
public class ContactsFragment extends Fragment {
    private  String TAG = "ContactsFragment";
    private MainActivity mActivity;
    private CloudGroupListCenter mCenter;
    private PreferenceUtil mPreferenceUtil;
    private String mUid;
    private LayoutInflater mInflater;
    private AllDialogUtil mDialogUtil;
    private Dialog mProgress;
    private CloudGroupAdapter mAdapter;
    private TextView mLocalUserMsg;
    private View mMainView;
    private LinearLayout mLlHelp;

    private ArrayList<CloudGroup> mGroupListData = new ArrayList<CloudGroup>();
    private CloudGroup localContact = new CloudGroup();
    //顶部titlebar
    private RelativeLayout mTitleBar;
    //右上角按钮
    private TextView mTvInAttendance;
    //号码群列表
    private ListView mCloudList;
    private CloudDBOperation mCloudDBOperation;
    private int mPosition;
    //创建订阅的弹窗
    private PopupWindow mOperatePopWindow;
    private boolean isLoading = false;

    private  final int MSG_REMOVE_GROUP = 7;
    protected ImageLoader imageLoader = ImageLoader.getInstance();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REMOVE_GROUP:
                    if (msg.arg1 == 0) {
                        final Long gid = (Long) msg.obj;
                        mGroupListData.remove(mPosition);
                        mAdapter.updateCloudGroupList(mGroupListData);

                        new AsyncTask<Void, Void, Void>() {

                            @Override
                            protected Void doInBackground(Void... voids) {
                                mCloudDBOperation.deleteGroupByGroupId(gid + "");
                                mCloudDBOperation.deleteContactByGroupId(mUid, gid + "");
                                return null;
                            }
                        }.execute();

                        //setCloudListData();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (MainActivity) getActivity();
        mCenter = CloudGroupListCenter.getInstance(mActivity);
        mPreferenceUtil = PreferenceUtil.getInstance(mActivity);
        mInflater = LayoutInflater.from(mActivity);
        mDialogUtil = AllDialogUtil.getInstance(mActivity);
        mProgress = mDialogUtil.styleProgress("请稍等...");
        mCloudDBOperation = new CloudDBOperation(mActivity);
        if (ContactsDBReader.ALL_CONTACTS_NUMBER == 0 || ContactsDBReader.mGroupList.isEmpty() || ContactsDBReader.mNoGroupsSet.isEmpty()) {
            ContactsDBReader.resetAllContactsNumber(mActivity);
        }
        localContact.groupName = "本地通讯录";
        localContact.contactCount = ContactsDBReader.ALL_CONTACTS_NUMBER;

        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
//        new UpLoadContactsTask(mActivity).execute();
        Log.i(TAG, "onCreate");
    }

    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.contacts_frag_layout, container, false);
            mTitleBar = (RelativeLayout) rootView.findViewById(R.id.rl_groupfrag_titlebar);
            mTvInAttendance = (TextView) rootView.findViewById(R.id.btn_in_attendance);
            mLlHelp = (LinearLayout) rootView.findViewById(R.id.contact_ll_help);
            mLlHelp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, WebViewActivity.class);
                    intent.putExtra("title", "手机如何创建新团队?");
                    intent.putExtra("type", 11);
                    startActivity(intent);
                }
            });
            mTvInAttendance.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, AttendanceMainActivity.class);
                    startActivity(intent);
                }
            });
            mCloudList = (ListView) rootView.findViewById(R.id.list_cloud);
            mCloudList.setOnItemClickListener(new MyOnItemClickListener());
            mCloudList.setOnItemLongClickListener(new MyOnItemLongClickListeneer());
        }
        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        isLoading = false;
        Log.d("GroupFragment", "onCreateView");
        return rootView;
    }


    public View initHeadView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.cloud_group_list_head_item, null);
        mLocalUserMsg = (TextView) view.findViewById(R.id.group_use_msg);
        return view;
    }

    public View initFootView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.cloud_group_list_foot_item, null);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        //if (!mActivity.mIsKeyBoardVisible) {
        Log.i(TAG, "onResume");
        boolean isFirst = mPreferenceUtil.getBoolean("create_group_v1", true);
        mActivity.showHelp(isFirst);
        setCloudListData();
        /*if (isLoading) {
            setCloudListData();
        } else {
            initGroupListData();
        }*/
        //   }
//        applyScrollListener();
//        mLocalUserMsg.setText(ContactsDBReader.ALL_CONTACTS_NUMBER + "个联系人");

    }

    private void applyScrollListener() {
        if (mActivity != null) {
            mCloudList.setOnScrollListener(new PauseOnScrollListener(imageLoader, false, true));
        }
    }


    private void initGroupListData() {
        /*new AsyncTask<String, Void, ArrayList<CloudGroup>>() {
            @Override
            protected ArrayList<CloudGroup> doInBackground(String... params) {
                ArrayList<CloudGroup> mLocalGroupList  = mCloudDBOperation.getLocalGroupList();
                return mLocalGroupList;
            }

            @Override
            protected void onPostExecute(ArrayList<CloudGroup> mLocalGroupList) {
                super.onPostExecute(mLocalGroupList);
                mGroupListData.clear();
                mGroupListData.add(localContact);
                mGroupListData.addAll(mLocalGroupList);
                mGroupListData.add(localContact);
                mAdapter.updateCloudGroupList(mGroupListData);
            }
        }.execute();*/
        if (mGroupListData != null) {
            mGroupListData.clear();
            mGroupListData.add(localContact);
            mGroupListData.addAll(mCloudDBOperation.getLocalGroupList(mUid));
            mGroupListData.add(localContact);
        }
        if (mAdapter != null) {
            mAdapter.updateCloudGroupList(mGroupListData);
        } else {
            mAdapter = new CloudGroupAdapter(mActivity, imageLoader);
            mCloudList.setAdapter(mAdapter);
            mAdapter.updateCloudGroupList(mGroupListData);
        }

    }


    /**
     * 设置号码群群列表数据
     */
    private void setCloudListData() {
//        mProgress.show();
        mGroupListData.clear();
        mGroupListData.add(localContact);
        mGroupListData.addAll(mCenter.getCloudGroupList(mActivity,mUid));
        mGroupListData.add(localContact);
        if (mAdapter != null) {
            mAdapter.updateCloudGroupList(mGroupListData);
        } else {
            mAdapter = new CloudGroupAdapter(mActivity, imageLoader);
            mCloudList.setAdapter(mAdapter);
            mAdapter.updateCloudGroupList(mGroupListData);
        }
        mCenter.setGroupListListener(new CloudGroupListCenter.CloudGroupDataListener() {
            @Override
            public void onChange(ArrayList<CloudGroup> groupList) {
                mGroupListData.clear();
                mGroupListData.add(localContact);
                mGroupListData.addAll(groupList);
                mGroupListData.add(localContact);
                mAdapter.updateCloudGroupList(mGroupListData);
                mProgress.dismiss();
//                mCloudList.onRefreshComplete("最近更新：" + DateUtil.getUpDateTime(System.currentTimeMillis()));

            }

            @Override
            public void onNoChange(ArrayList<CloudGroup> groupList) {
                mAdapter.updateCloudGroupList(mGroupListData);
                if (mProgress != null && mProgress.isShowing()) {
                    mProgress.dismiss();
                }
//                mCloudList.onRefreshComplete("最近更新：" + DateUtil.getUpDateTime(System.currentTimeMillis()));

            }

            @Override
            public void onError(int errNum, String obj) {
                if (mProgress != null && mProgress.isShowing()) {
                    mProgress.dismiss();
                }
                if (errNum == 1002 || errNum == 1003 || errNum == 1005){
                    backToLogin(obj);
                }else{
                    Toast.makeText(mActivity, obj, Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    private void createGroup() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(mActivity, CreateGroupActivity.class));
        mActivity.startActivity(intent);
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mProgress != null && mProgress.isShowing()) {
            mProgress.dismiss();
            mProgress = null;
        }
    }

    /**
     * 进入分组监听
     */
    class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (Constants.isFastClick()) {
                return;
            }
            isLoading = true;
            if (mGroupListData.size() == 0) {
                mGroupListData.add(localContact);
                mGroupListData.addAll(mCenter.getCloudGroupList(mActivity,mUid));
                mGroupListData.add(localContact);
            }
            if (i == 0) {
                Intent intent = new Intent(mActivity, CloudDialerActivity.class);
                intent.setAction("local_contact_list");
                startActivity(intent);
            } else if (i == (mGroupListData.size() - 1)) {
                createGroup();
            } else {
                if (mGroupListData != null) {
                    Adapter adapter = adapterView.getAdapter();
                    CloudGroup item = (CloudGroup) adapter.getItem(i);
                    CloudDialerActivity.selectedGroup = item;
                    CloudDialerActivity.selectedGroup.position = i;
                    Intent intent = new Intent(mActivity, CloudDialerActivity.class);
                    intent.setAction("cloud_contact_list");
                    intent.putExtra("group_id", mGroupListData.get(i).groupId + "");
                    intent.putExtra("tag_id", "0");
                    intent.putExtra("tag_name", mGroupListData.get(i).groupName);
                    intent.putExtra("group_name", mGroupListData.get(i).groupName);
                    intent.putExtra("pid", "");
                    intent.putExtra("contact_id", mGroupListData.get(i).contactId);
                    intent.putExtra("group_img", mGroupListData.get(i).groupImg);
                    intent.putExtra("group_type", mGroupListData.get(i).groupType);
                    intent.putExtra("user_type", mGroupListData.get(i).userType);
                    intent.putExtra("contact_count", mGroupListData.get(i).contactCount);
                    startActivity(intent);
                }
            }
        }
    }

    /**
     * 退组监听
     */
    class MyOnItemLongClickListeneer implements AdapterView.OnItemLongClickListener {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
            if (position == 0) {

            } else if (position == (mGroupListData.size() - 1)) {
            } else {
                Adapter adapter = parent.getAdapter();
                if (CloudGroupAdapter.ITEM_TYPE_CLOUD_GROUP_ITEM == adapter.getItemViewType(position)) {
                    CloudGroup item = (CloudGroup) adapter.getItem(position);
                    mPosition = position;
                    showExitGroupDlg(item);

                }
            }
            return true;
        }
    }

    /**
     * 退出群组
     *
     * @param groupItem
     */
    public void showExitGroupDlg(final CloudGroup groupItem) {
        String okText = mActivity.getString(R.string.label_btn_ok);
        String cancelText = mActivity.getString(R.string.cancel);
        if (groupItem.userType.equals("3")) {
            mDialogUtil.titleDeleteMsgStyle("解散" + groupItem.groupName + "号码簿", okText, cancelText, "号码簿解散后,所有成员将失去此号码簿。此动作不可恢复,是否确认解散?");
        } else {
            mDialogUtil.titleDeleteMsgStyle("退出" + groupItem.groupName + "号码簿", okText, cancelText, "退出号码簿后,所有成员将失去您的联系方式。是否确认退出?");
        }
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                exitGroup(groupItem.groupId, groupItem.contactId);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();

            }
        });
    }


    private void exitGroup(long groupId, String contactId) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, String.valueOf(groupId)));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_ID, contactId));
        Message callback = mHandler.obtainMessage(MSG_REMOVE_GROUP);
        callback.obj = Long.valueOf(groupId);
        WithoutObjMsg msg = new WithoutObjMsg(callback);
        msg.mParams = params;
        msg.mApi = AsynHttpClient.API_GROUP_REMOVE;
        AsynHttpClient.getInstance(mActivity).execCcHttp(msg);
    }

    /**
     * 跳转登录页面
     * @param messsge
     */
    private void backToLogin(String messsge){
        mDialogUtil.titleMsgBtnStyle("提示", messsge, mActivity.getString(R.string.ok));
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {

                lDialog.dismiss();
                Intent intent = new Intent(mActivity, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mActivity.startActivity(intent);
                mActivity.finish();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
            }
        });
    }


    //回调机制更新此Fragment的方法
    public void update() {
        setCloudListData();
    }
}